import { ElMessage } from 'element-plus';

export const clientHost = () => {
    return 'localhost'
}

export const serverHost = () => {
    return 'localhost'
}

export const port = () => {
    return import.meta.env.MODE === 'production' ? 3900 : 3900;
}

// 每次启动都获取最新的网络信息
export const updateNetorkInfo = async () => {
    const info = await window.ipc.getNetworkInfo()
    localStorage.setItem('network_info', JSON.stringify(info)); // 存入LocalStorage（临时会话存储）
    console.log(`通过ipc获取的网络信息：`, info)
    return info
}

export const parseNetworkInfo = () => {
    let networkInfo, source;
    try {
        const stored = localStorage.getItem('network_info')
        if (stored) {
            console.log('存缓存获取到的数据是：：', stored)
            networkInfo = JSON.parse(stored);
            source = '缓存';
            // ElMessage.success('从缓存获取到ip信息');
            console.log('从缓存获取到ip信息')
        } else {
            const url = new URL(window.location.href)
            const [ip, clientPort] = url.host.split(':')

            // 1. 提取查询字符串部分
            const queryString = url.href.split('?')[1] || ''; // 得到 "st=3900"
            // 2. 正则匹配 st 参数的值
            const serverPort = queryString.match(/(?:^|&)st=(\d+)/)?.[1];

            networkInfo = { ip, clientPort, "serverPort": serverPort }

            localStorage.setItem('network_info', JSON.stringify(networkInfo))
            source = 'url解析';

            // ElMessage.warning('从url里面获取ip信息并缓存起来');
            console.log('从url里面获取ip信息并缓存起来')
        }
        return { networkInfo, source }
    } catch {
        console.log('没有获取到ip信息')
        return false
    }
}
